import api from './api';
import { hashPassword } from '../utils/encryption';

class AuthService {
  // Login user
  async login(credentials) {
    try {
      // Hash the password before sending
      const hashedCredentials = {
        ...credentials,
        password: hashPassword(credentials.password)
      };
      
      // Use encryption for sensitive data
      const response = await api.post('/auth/login', hashedCredentials, true);
      
      // Store token in localStorage
      if (response.token) {
        localStorage.setItem('authToken', response.token);
        localStorage.setItem('user', JSON.stringify(response.user));
      }
      
      return response;
    } catch (error) {
      throw new Error(error.message || 'Login failed');
    }
  }

  // Register new user
  async register(userData) {
    try {
      // Hash the password before sending
      const hashedUserData = {
        ...userData,
        password: hashPassword(userData.password)
      };
      
      // Use encryption for sensitive data
      const response = await api.post('/auth/register', hashedUserData, true);
      
      // Store token in localStorage if registration includes auto-login
      if (response.token) {
        localStorage.setItem('authToken', response.token);
        localStorage.setItem('user', JSON.stringify(response.user));
      }
      
      return response;
    } catch (error) {
      throw new Error(error.message || 'Registration failed');
    }
  }

  // Logout user
  async logout() {
    try {
      await api.post('/auth/logout');
    } catch (error) {
      console.error('Logout error:', error);
    } finally {
      // Always clear local storage
      localStorage.removeItem('authToken');
      localStorage.removeItem('user');
    }
  }

  // Refresh token
  async refreshToken() {
    try {
      const response = await api.post('/auth/refresh');
      
      if (response.token) {
        localStorage.setItem('authToken', response.token);
      }
      
      return response;
    } catch (error) {
      // If refresh fails, logout user
      this.logout();
      throw new Error('Session expired, please login again');
    }
  }

  // Get current user
  async getCurrentUser() {
    try {
      const response = await api.get('/auth/me');
      return response.user;
    } catch (error) {
      throw new Error(error.message || 'Failed to get user information');
    }
  }

  // Reset password request
  async requestPasswordReset(email) {
    try {
      const response = await api.post('/auth/forgot-password', { email });
      return response;
    } catch (error) {
      throw new Error(error.message || 'Failed to send reset email');
    }
  }

  // Reset password with token
  async resetPassword(token, newPassword) {
    try {
      // Hash the new password before sending
      const hashedData = {
        token,
        password: hashPassword(newPassword),
      };
      
      // Use encryption for sensitive data
      const response = await api.post('/auth/reset-password', hashedData, true);
      return response;
    } catch (error) {
      throw new Error(error.message || 'Failed to reset password');
    }
  }

  // Check if user is authenticated
  isAuthenticated() {
    const token = localStorage.getItem('authToken');
    return !!token;
  }

  // Get stored user
  getStoredUser() {
    const user = localStorage.getItem('user');
    return user ? JSON.parse(user) : null;
  }
}

export default new AuthService();